<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改渠道代理商')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <style>
        .form-group label {
            font-weight: 600;
        }
        .preview-img {
            max-width: 200px;
            max-height: 150px;
            margin-top: 10px;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-agent-edit" th:object="${channelAgent}">
        <input name="id" th:field="*{id}" type="hidden"/>

        <!-- 隐藏的JSON字段，提交时用 -->
        <input name="contactInfo" th:field="*{contactInfo}" type="hidden"/>
        <input name="baseInfo" th:field="*{baseInfo}" type="hidden"/>
        <input name="settleInfo" th:field="*{settleInfo}" type="hidden"/>
        <input name="businessInfo" th:field="*{businessInfo}" type="hidden"/>
        <input name="picturesInfo" th:field="*{picturesInfo}" type="hidden"/>
        <input name="agentId" th:field="*{agentId}" type="hidden"/>
        <input name="status" th:field="*{status}" type="hidden"/>

        <h4>渠道选择</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">渠道：</label>
                    <div class="col-sm-8">
                        <select name="channelCode" class="form-control m-b"   th:field="*{channelCode}"
                                th:with="type=${@dict.getType('channel_type')}">
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <!-- 联系人信息 contactInfo -->
        <h4>联系人信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">代理商账号：</label>
                    <div class="col-sm-8">
                        <input id="contact_agentAccount" name="contact_agentAccount" class="form-control" type="text"
                               maxlength="50" placeholder="代理商账号"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">联系人邮箱：</label>
                    <div class="col-sm-8">
                        <input id="contact_contactEmail" name="contact_contactEmail" class="form-control" type="email"
                               maxlength="100" placeholder="邮箱"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">联系人手机：</label>
                    <div class="col-sm-8">
                        <input id="contact_contactMobile" name="contact_contactMobile" class="form-control" type="text"
                               maxlength="20" placeholder="手机号"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6"></div> <!-- 空列 -->
        </div>

        <!-- 基础信息 baseInfo -->
        <h4>基础信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <input id="addBd" name="addBd" class="form-control" type="hidden"/>
                    <input id="agentParentId" name="agentParentId" class="form-control" type="hidden"/>
                    <input id="legalPersonMobile" name="legalPersonMobile" class="form-control" type="hidden"/>
                    <label class="col-sm-4 control-label">代理商性质：</label>
                    <div class="col-sm-8">
                        <select id="agentProperty" name="agentProperty" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="0">企业</option>
                            <option value="1">个人</option>
                            <option value="2">个体工商户</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">公司名称：</label>
                    <div class="col-sm-8">
                        <input id="enterpriseTitle" name="enterpriseTitle" class="form-control" type="text"
                               maxlength="100" placeholder="公司名称"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">统一社会信用代码：</label>
                    <div class="col-sm-8">
                        <input id="creditCode" name="creditCode" class="form-control" type="text" maxlength="50"
                               placeholder="统一社会信用代码"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">法人证件有效期：</label>
                    <div class="col-sm-8">
                        <input id="legalPersonCertEndDate" name="legalPersonCertEndDate" class="form-control"
                               type="text" maxlength="200" placeholder="法人证件结束值长期，则填写“永久有效”"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">营业执照有效期：</label>
                    <div class="col-sm-8">
                        <input id="businessLicenseEndDate" name="businessLicenseEndDate" class="form-control"
                               type="text" maxlength="200" placeholder="营业执照有效期"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">法人姓名：</label>
                    <div class="col-sm-8">
                        <input id="legalPersonName" name="legalPersonName" class="form-control" type="text"
                               maxlength="20" placeholder="法人姓名"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">法人身份证号：</label>
                    <div class="col-sm-8">
                        <input id="legalPersonIdCard" name="legalPersonIdCard" class="form-control" type="text"
                               maxlength="18" placeholder="身份证号"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">所在区域：</label>
                    <div class="col-sm-3">
                        <input id="agentProvince" name="agentProvince" class="form-control" type="text" maxlength="100"
                               placeholder="所在区域"/>
                    </div>
                    <div class="col-sm-3">
                        <input id="agentCity" name="agentCity" class="form-control" type="text" maxlength="100"
                               placeholder="所在区域"/>
                    </div>
                    <div class="col-sm-2">
                        <input id="province" name="province" class="form-control" type="text" maxlength="100"
                               placeholder="所在区域"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">地址：</label>
                    <div class="col-sm-8">
                        <input id="agentAddress" name="agentAddress" class="form-control" type="text" maxlength="200"
                               placeholder="地址"/>
                    </div>
                </div>
            </div>
        </div>


        <!-- 结算信息 settleInfo -->
        <h4>结算信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">银行卡号：</label>
                    <div class="col-sm-8">
                        <input id="bankAccountNo" name="bankAccountNo" class="form-control" type="text" maxlength="30"
                               placeholder="银行卡号"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">开户人：</label>
                    <div class="col-sm-8">
                        <input id="bankCardHolder" name="bankCardHolder" class="form-control" type="text" maxlength="50"
                               placeholder="开户人"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">银行编码：</label>
                    <div class="col-sm-8">
                        <input id="bankId" name="bankId" class="form-control" type="text" maxlength="30"
                               placeholder="银行编码"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">联行号：</label>
                    <div class="col-sm-8">
                        <input id="bankUnionpayCode" name="bankUnionpayCode" class="form-control" type="text"
                               maxlength="30" placeholder="联行号"/>
                    </div>
                </div>
            </div>

        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">账号类型：</label>
                    <div class="col-sm-8">
                        <select id="bankAccountType" name="bankAccountType" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="1">对私</option>
                            <option value="2">对公</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">结算方式：</label>
                    <div class="col-sm-8">
                        <select id="settObType" name="settObType" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="legalPerson">法人结算</option>
                            <option value="company">对公结算</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">银行预留手机号：</label>
                    <div class="col-sm-8">
                        <input id="bankMobile" name="bankMobile" class="form-control" type="text" maxlength="30"
                               placeholder="银行预留手机号"/>
                    </div>
                </div>
            </div>
        </div>
        <!-- 交易结算信息 businessInfo -->
        <h4>交易结算信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">分润模式：</label>
                    <div class="col-sm-8">
                        <select id="drawPattern" name="drawPattern" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="1">按天（代发）</option>
                            <option value="2">按月（不代发）</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">分成模式：</label>
                    <div class="col-sm-8">
                        <select id="profitRuleType" name="profitRuleType" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="0">成本规则</option>
                            <option value="1">SaaS 高签</option>
                            <option value="2">成本比例高签</option>
                            <option value="3">刷宝3.0</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">分成比例:(0-100的整数)</label>
                    <div class="col-sm-8">
                        <input id="lowerDivideCent" name="lowerDivideCent" class="form-control" type="text"
                               maxlength="30" placeholder="分成比例"/>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">是否独立结算：</label>
                    <div class="col-sm-8">
                        <select id="subProfitBillFlag" name="subProfitBillFlag" class="form-control" required>
                            <option value="">请选择</option>
                            <option value="0">否</option>
                            <option value="1">是</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <!-- 图片信息展示 -->
        <h4>图片信息展示</h4>
        <div class="row">
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">身份证人像面：</label>
                    <div class="col-sm-8">
                        <input type="file" accept="image/*" class="form-control image-input" data-type="idCardFrontPic" name="idCardFrontPic">
                        <div class="preview-box" id="preview-idCardFrontPic"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">身份证国徽面：</label>
                    <div class="col-sm-8">
                        <input type="file" accept="image/*" class="form-control image-input" data-type="idCardBackPic" name="idCardBackPic">
                        <div class="preview-box" id="preview-idCardBackPic"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-4" data-show-type="private">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">结算银行卡正面：</label>
                    <div class="col-sm-8">
                        <input type="file" accept="image/*" class="form-control image-input" data-type="settleBankCardFrontPic"  name="settleBankCardFrontPic">
                        <div class="preview-box" id="preview-settleBankCardFrontPic"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-4" data-show-type="enterprise">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">营业执照复印件：</label>
                    <div class="col-sm-8">
                        <input type="file" accept="image/*" class="form-control image-input" data-type="businessLicensePic"  name="businessLicensePic">
                        <div class="preview-box" id="preview-businessLicensePic"></div>
                    </div>
                </div>
            </div>
            <div class="col-sm-4" data-show-type="enterprise">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">开户许可证/企业账户截图：</label>
                    <div class="col-sm-8">
                        <input type="file" accept="image/*" class="form-control image-input" data-type="publicAccountPic"  name="publicAccountPic">
                        <div class="preview-box" id="preview-publicAccountPic"></div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>

<script th:inline="javascript">
    /* 将Java对象转换为JS对象 */
    var agentPicturesInfo = /*[[${agentPicturesInfo}]]*/ {};

    var prefix = ctx + "channel/agent";
    var channelType = [[${@dict.getType('channel_type')}]];

    $(function () {
        // 解析 contactInfo
        try {
            var contact = JSON.parse($("input[name='contactInfo']").val() || '{}');
            $("#contact_agentAccount").val(contact.agentAccount || '');
            $("#contact_contactEmail").val(contact.contactEmail || '');
            $("#contact_contactMobile").val(contact.contactMobile || '');
        } catch (e) {
            console.warn("contactInfo 解析失败");
        }

        // 解析 baseInfo
        try {
            var base = JSON.parse($("input[name='baseInfo']").val() || '{}');
            $("#enterpriseTitle").val(base.enterpriseTitle || '');
            $("#creditCode").val(base.creditCode || '');
            $("#legalPersonName").val(base.legalPersonName || '');
            $("#legalPersonIdCard").val(base.legalPersonIdCard || '');
            $("#base_area").val(base.area || '');
            $("#agentAddress").val(base.agentAddress || '');
            $("#businessLicenseEndDate").val(base.businessLicenseEndDate || '');
            $("#legalPersonCertEndDate").val(base.legalPersonCertEndDate || '');
            $("#agentProperty").val(base.agentProperty || '');
            $("#agentProvince").val(base.agentProvince || '');
            $("#agentCity").val(base.agentCity || '');
            $("#province").val(base.province || '');
            $("#addBd").val(base.addBd || '');
            $("#agentParentId").val(base.agentParentId || '');
            $("#legalPersonMobile").val(base.legalPersonMobile || '');
        } catch (e) {
            console.warn("baseInfo 解析失败", e);
        }

        // 解析 settleInfo
        try {
            var settle = JSON.parse($("input[name='settleInfo']").val() || '{}');
            $("#bankAccountNo").val(settle.bankAccountNo || '');
            $("#bankCardHolder").val(settle.bankCardHolder || '');
            $("#bankUnionpayCode").val(settle.bankUnionpayCode || '');
            $("#bankId").val(settle.bankId || '');
            $("#bankMobile").val(settle.bankMobile || '');
            $("#settObType").val(settle.settObType || '');
            $("#bankAccountType").val(settle.bankAccountType || '');
        } catch (e) {
            console.warn("settleInfo 解析失败");
        }

        // 解析 businessInfo
        try {
            var business = JSON.parse($("input[name='businessInfo']").val() || '{}');
            $("#drawPattern").val(business.drawPattern || '');
            $("#profitRuleType").val(business.profitRuleType || '');
            $("#lowerDivideCent").val(business.lowerDivideCent || '');
            $("#subProfitBillFlag").val(business.subProfitBillFlag || '');
        } catch (e) {
            console.warn("businessInfo 解析失败");
        }

        function toggleEnterpriseFields(value) {
            const shouldHide = value === '1'; // 个人
            const isPrivate = value === '1'; // 1表示对私，2为对公
            const enterpriseFields = [
                '#enterpriseTitle',
                '#creditCode',
                '#businessLicenseEndDate'
            ];
            enterpriseFields.forEach(selector => {
                $(selector).closest('.form-group').toggle(!shouldHide);
            });
            // 控制图片上传区域显示
            $('[data-show-type="private"]').toggle(isPrivate);
            $('[data-show-type="enterprise"]').toggle(!isPrivate);
        }
        toggleEnterpriseFields($("#agentProperty").val());
        $("#agentProperty").on("change", function () {
            toggleEnterpriseFields($(this).val());
        });
    });

    function submitHandler() {
        var contactObj = {
            agentAccount: $("#contact_agentAccount").val(),
            contactEmail: $("#contact_contactEmail").val(),
            contactMobile: $("#contact_contactMobile").val()
        };
        $("input[name='contactInfo']").val(JSON.stringify(contactObj));

        var baseObj = {
            enterpriseTitle: $("#enterpriseTitle").val(),
            creditCode: $("#creditCode").val(),
            legalPersonName: $("#legalPersonName").val(),
            legalPersonIdCard: $("#legalPersonIdCard").val(),
            area: $("#base_area").val(),
            agentAddress: $("#agentAddress").val(),
            businessLicenseEndDate: $("#businessLicenseEndDate").val(),
            legalPersonCertEndDate: $("#legalPersonCertEndDate").val(),
            agentProperty: $("#agentProperty").val(),
            agentProvince: $("#agentProvince").val(),
            addBd: $("#addBd").val(),
            agentParentId: $("#agentParentId").val(),
            legalPersonMobile: $("#legalPersonMobile").val(),
            agentCity: $("#agentCity").val(),
            province: $("#province").val()
        };
        $("input[name='baseInfo']").val(JSON.stringify(baseObj));

        var settleObj = {
            bankAccountNo: $("#bankAccountNo").val(),
            bankCardHolder: $("#bankCardHolder").val(),
            bankUnionpayCode: $("#bankUnionpayCode").val(),
            bankId: $("#bankId").val(),
            bankMobile: $("#bankMobile").val(),
            settObType: $("#settObType").val(),
            bankAccountType: $("#bankAccountType").val()
        };
        $("input[name='settleInfo']").val(JSON.stringify(settleObj));

        var businessObj = {
            drawPattern: $("#drawPattern").val(),
            profitRuleType: $("#profitRuleType").val(),
            lowerDivideCent: $("#lowerDivideCent").val(),
            subProfitBillFlag: $("#subProfitBillFlag").val()
        };
        $("input[name='businessInfo']").val(JSON.stringify(businessObj));

        var form = document.getElementById('form-agent-edit');
        var formData = new FormData(form);
        if ($.validate.form()) {
            // 用Ajax提交
            $.ajax({
                url: prefix + "/edit",
                type: 'POST',
                data: formData,
                processData: false, // 不处理数据
                contentType: false, // 不设置Content-Type，让浏览器自动处理multipart/form-data
                success: function(res) {
                    // 成功处理
                    $.operate.successCallback(res);
                },
                error: function(err) {
                    $.modal.alertError("修改失败");
                }
            });
        }
    }

    // 页面加载时展示已有图片
    window.onload = function () {
        renderPreview('idCardFrontPic', agentPicturesInfo.idCardFrontPic);
        renderPreview('idCardBackPic', agentPicturesInfo.idCardBackPic);
        renderPreview('settleBankCardFrontPic', agentPicturesInfo.settleBankCardFrontPic);
        renderPreview('businessLicensePic', agentPicturesInfo.businessLicensePic);
        renderPreview('publicAccountPic', agentPicturesInfo.publicAccountPic);
    };

    // 监听文件选择
    document.addEventListener('change', function (e) {
        if (e.target.classList.contains('image-input')) {
            const fileInput = e.target;
            const file = fileInput.files[0];
            const type = fileInput.getAttribute('data-type');

            if (file && type) {
                const reader = new FileReader();
                reader.onload = function (event) {
                    renderPreview(type, event.target.result);
                };
                reader.readAsDataURL(file);
            }
        }
    });

    // 图片预览渲染
    function renderPreview(type, imageUrl) {
        const box = document.getElementById('preview-' + type);
        if (box && imageUrl) {
            box.innerHTML = `<img src="${imageUrl}" class="img-thumbnail preview-img" style="max-height: 150px;">`;
        }
    }
</script>


</body>
</html>
